package com.hyt.it.ogt.ykcj.service.grade.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hyt.it.ogt.ykcj.common.utils.MathUtils;
import com.hyt.it.ogt.ykcj.domain.exam.ExamStemInfo;
import com.hyt.it.ogt.ykcj.domain.grade.ServantInterviewAnalysisData;
import com.hyt.it.ogt.ykcj.domain.grade.ServantPassAnalysisData;
import com.hyt.it.ogt.ykcj.domain.grade.ServantSubjectPtGradeAnalysisData;
import com.hyt.it.ogt.ykcj.domain.vo.GradeAnalysisDataVo;
import com.hyt.it.ogt.ykcj.domain.vo.QueryExamineeGradeVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp.InterviewAnalysisDataVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp.ServantAnalysisInterviewVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp.ServantAnalysisPassVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp.ServantAnalysisPositionVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisRsp.ServantPassAnalysisDataVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeAnalysisYearVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeSubjectAnalysisVo;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeSubjectAnalysisVo.ServantGradeSubjectAnalysisItem;
import com.hyt.it.ogt.ykcj.domain.vo.ServantGradeSubjectAnalysisVo.ServantGradeSubjectStem;
import com.hyt.it.ogt.ykcj.domain.vo.ServantInterviewAnalysisDataResp;
import com.hyt.it.ogt.ykcj.service.exam.IExamStemInfoService;
import com.hyt.it.ogt.ykcj.service.grade.IGradeAnalysisDataService;
import com.hyt.it.ogt.ykcj.service.grade.IServantGradeAnalysisDataService;
import com.hyt.it.ogt.ykcj.service.grade.IServantInterviewAnalysisDataService;
import com.hyt.it.ogt.ykcj.service.grade.IServantPassAnalysisDataService;
import com.hyt.it.ogt.ykcj.service.grade.IServantSubjectPtGradeAnalysisDataService;

/**
 * @author gaokx
 * @Description
 * @create 2021-11-02 12:42
 **/
@Service
public class ServantGradeAnalysisDataServiceImpl implements IServantGradeAnalysisDataService {
  @Autowired
  private IGradeAnalysisDataService gradeAnalysisDataService;
  @Autowired
  private IServantSubjectPtGradeAnalysisDataService servantSubjectPtGradeAnalysisDataService;
  @Autowired
  private IServantInterviewAnalysisDataService  servantInterviewAnalysisDataService;
  @Autowired
  private IServantPassAnalysisDataService servantPassAnalysisDataService ;
  @Autowired
  private IExamStemInfoService examStemInfoService ;

  @Override
  public ServantGradeAnalysisRsp selectServantGradeAnalysisData(QueryExamineeGradeVo query) {
    ServantGradeAnalysisRsp rsp = new ServantGradeAnalysisRsp();
    String examNameConfigId = query.getExamNameConfigId();
    String examYear = query.getExamYear();
    String examId = query.getExamId();
    //查询公用统计报表
    // 考试id不为空时是当前考试成绩总体概况。为空时是当年成绩总体概况
    GradeAnalysisDataVo curGradeAnalysisData = gradeAnalysisDataService.getYearDataVo(examNameConfigId,examYear,examId);
    if(null != curGradeAnalysisData){
      gradeAnalysisDataService.convertCurYearData(curGradeAnalysisData,examNameConfigId,examYear,examId);
    }
    //当前年份数据
    rsp.setCurDataAnalysis(curGradeAnalysisData);

    //按年份
    rsp.setTotalDataList(handleAnalysisDataByTotalSex(query));


    //按层级查询通过及实考
    List<ServantPassAnalysisDataVo> passAnalysisData   = handleServantGradeAnalysisDataPass(query);
    if(ObjectUtils.isNotEmpty(passAnalysisData)){
      rsp.setPassAnalysisData(passAnalysisData);
    }

    //查询机构面试统计列表
    List<InterviewAnalysisDataVo>   interviews = handleServantGradeAnalysisDataInterview(query);
    if(ObjectUtils.isNotEmpty(interviews)){
      rsp.setInterviewAnalysisData(interviews);
    }

    //查询机构面试统计图表--按职位
    handleServantGradeAnalysisDataInterviewZwlb(query, rsp);
    return rsp;
  }

  /**
   * 按科目做统计公务员成绩分析
   * @param query
   * @return
   */
  @Override
  public ServantGradeSubjectAnalysisVo selectServantSubjectGradeAnalysisData(QueryExamineeGradeVo query) {
    return handleServantGradeAnalysisDataSubject(query);
  }

  public ServantGradeSubjectAnalysisVo handleServantGradeAnalysisDataSubject(QueryExamineeGradeVo query) {
    ServantGradeSubjectAnalysisVo sgaResult = new ServantGradeSubjectAnalysisVo();
    ServantSubjectPtGradeAnalysisData subjectGrade = new ServantSubjectPtGradeAnalysisData();
    subjectGrade.setExamId(query.getExamId());
    subjectGrade.setExamYear(query.getExamYear());
    subjectGrade.setExamNameConfigId(query.getExamNameConfigId());
    subjectGrade.setSubjectId(query.getSubjectId());
    ExamStemInfo examStemInfo = new ExamStemInfo();
    examStemInfo.setSubjectId(query.getSubjectId());
    Map<String,Object> params = new HashMap<>();
    params.put("orderBy", "sort");
    examStemInfo.setParams(params);
    List<ExamStemInfo> basicStemInfos = examStemInfoService.selectExamStemInfoList(examStemInfo);
    List<ServantSubjectPtGradeAnalysisData> gradeAnalysisData = servantSubjectPtGradeAnalysisDataService.selectServantSubjectPtGradeAnalysisDataList(subjectGrade);
    List<ServantSubjectPtGradeAnalysisData> stemAvgRights= servantSubjectPtGradeAnalysisDataService.selectAvgScoreByStem(subjectGrade);
    Map<String,ServantSubjectPtGradeAnalysisData> stemAvgMap = stemAvgRights.stream().collect(Collectors.toMap(ServantSubjectPtGradeAnalysisData::getExamStemId, e -> e));
    List<ServantGradeSubjectStem> stemInfos = new ArrayList<>();
    for(ExamStemInfo esi : basicStemInfos ){
      ServantGradeSubjectStem subjectStem = new ServantGradeSubjectStem();
      subjectStem.setExamStemId(esi.getId());
      subjectStem.setExamStemName(esi.getName());
      subjectStem.setTitleNumber(esi.getTitleNumber());
      subjectStem.setTotalPoints(esi.getTotalPoints());
      if(stemAvgMap.containsKey(subjectStem.getExamStemId())){
        ServantSubjectPtGradeAnalysisData  stemAvg = stemAvgMap.get(subjectStem.getExamStemId());
        subjectStem.setAvgScore(stemAvg.getAvgScore());
        subjectStem.setMaleAvgScore(stemAvg.getMaleAvgScore());
        subjectStem.setFemaleAvgScore(stemAvg.getFemaleAvgScore());
        subjectStem.setRightRate(stemAvg.getRightRate());
        subjectStem.setMaleRightRate(stemAvg.getMaleRightRate());
        subjectStem.setFemaleRightRate(stemAvg.getFemaleRightRate());
      }
      stemInfos.add(subjectStem);
    }
    List<ServantGradeSubjectAnalysisItem> analysisItems = new ArrayList<>();
    Map<String,List<ServantSubjectPtGradeAnalysisData>> dataMap = gradeAnalysisData.stream().collect(Collectors.groupingBy(t -> t.getPositionTier()));

    Iterator<Map.Entry<String,List<ServantSubjectPtGradeAnalysisData>>> iterators = dataMap.entrySet().iterator();
    while(iterators.hasNext()){
      Map<String,List> avgScoreMap =  new LinkedHashMap();
      ServantGradeSubjectAnalysisItem sgsai = new ServantGradeSubjectAnalysisItem();
      Map.Entry<String,List<ServantSubjectPtGradeAnalysisData>> entry = iterators.next();
      String positionTier = entry.getKey();
      List<ServantSubjectPtGradeAnalysisData> lists = entry.getValue();
      String positionTierName = CollectionUtils.isNotEmpty(lists)? lists.get(0).getPositionTierName():"";
      //再次按照题型分组
      Map<String,ServantSubjectPtGradeAnalysisData> stemMap = lists.stream().collect(Collectors.toMap(ServantSubjectPtGradeAnalysisData::getExamStemId, e -> e));
      List maleAvgList = new ArrayList();
      List femaleAvgList = new ArrayList();
      List avgScoreList = new ArrayList();
      List maleRightRateList = new ArrayList();
      List femaleRightRateList = new ArrayList();
      List rightRateList = new ArrayList();

      //按题序遍历
      for(ServantGradeSubjectStem esi : stemInfos ){
        String stemId = esi.getExamStemId();
        if(stemMap.containsKey(stemId)){
          ServantSubjectPtGradeAnalysisData  data = stemMap.get(stemId);
          maleAvgList.add(data.getMaleAvgScore());
          femaleAvgList.add(data.getFemaleAvgScore());
          avgScoreList.add(data.getAvgScore());
          maleRightRateList.add(data.getMaleRightRate());
          femaleRightRateList.add(data.getFemaleRightRate());
          rightRateList.add(data.getRightRate());
        }
      }
      if(CollectionUtils.isNotEmpty(maleAvgList)){
        avgScoreMap.put("男平均得分",maleAvgList);
      }
      if(CollectionUtils.isNotEmpty(femaleAvgList)){
        avgScoreMap.put("女平均得分",femaleAvgList);
      }
      if(CollectionUtils.isNotEmpty(avgScoreList)){
        avgScoreMap.put("全体平均得分",avgScoreList);
      }
      if(CollectionUtils.isNotEmpty(rightRateList)){
        avgScoreMap.put("合计正确率",rightRateList);
      }
      if(CollectionUtils.isNotEmpty(maleRightRateList)){
        avgScoreMap.put("男正确率",maleRightRateList);
      }
      if(CollectionUtils.isNotEmpty(femaleRightRateList)){
        avgScoreMap.put("女正确率",femaleRightRateList);
      }
      sgsai.setPositionTier(positionTier);
      sgsai.setPositionTierName(positionTierName);
      sgsai.setGroups(avgScoreMap);
      analysisItems.add(sgsai);
    }
    sgaResult.setExamStemInfo(stemInfos);
    sgaResult.setJgcjInfo(analysisItems);
    return sgaResult ;
  }

  /**
   * 总体概况
   * 按年份
   * @param query
   */
  private List<ServantGradeAnalysisYearVo>  handleAnalysisDataByTotalSex(QueryExamineeGradeVo query){
    List<ServantGradeAnalysisYearVo> dataYearList  = new ArrayList<>();
    //查询总体概况 ：实考趋势和整体合格率趋势
    List<GradeAnalysisDataVo> totalDataList = gradeAnalysisDataService.selectGradeAnalysisDataTotalListByIdAndYearList(query.getExamYear(), query.getExamNameConfigId(),query.getExamId());
    totalDataList.forEach(e -> {
      ServantGradeAnalysisYearVo yearVo = new ServantGradeAnalysisYearVo();
      BeanUtils.copyProperties(e, yearVo);
      dataYearList.add(yearVo);
    });

    //按性别统计
    List<GradeAnalysisDataVo> sexDataList = gradeAnalysisDataService.getGradeAnalysisDataBySexYearList(query.getExamNameConfigId(),query.getExamYear(),query.getExamId());
    Map<String,GradeAnalysisDataVo> sexDataMap =  new HashMap<>();
    if(!CollectionUtils.isEmpty(sexDataList)){
      sexDataMap= sexDataList.stream().filter(e -> "1".equals(e.getSex())).collect(Collectors.toMap(GradeAnalysisDataVo::getExamYear, Function.identity(), (key1, key2) -> key2));
    }
    if(!sexDataMap.isEmpty()){
      //填充性别数据
      for(ServantGradeAnalysisYearVo vo : dataYearList){
        if(sexDataMap.containsKey(vo.getExamYear())){
          vo.setMalePassRate(sexDataMap.get(vo.getExamYear()).getPassRate());
          vo.setMalePassNum(sexDataMap.get(vo.getExamYear()).getPassNum());
        }
      }
    }
    return dataYearList ;
  }

  private void  handleServantGradeAnalysisDataInterviewZwlb(QueryExamineeGradeVo query,ServantGradeAnalysisRsp result) {
    ServantInterviewAnalysisData queryData = new ServantInterviewAnalysisData();
    queryData.setExamId(query.getExamId());
    queryData.setExamNameConfigId(query.getExamNameConfigId());
    queryData.setExamYear(query.getExamYear());
    List<ServantInterviewAnalysisDataResp> list =   servantInterviewAnalysisDataService.getServantInterviewAnalysisDataByZwlb(queryData);
    List passInfos = new ArrayList();
    List interviewInfos = new ArrayList();
    List positionInfos = new ArrayList();
    for(ServantInterviewAnalysisDataResp dataResp : list){
      ServantAnalysisPassVo passInfo = new ServantAnalysisPassVo();
      BeanUtils.copyProperties(dataResp,passInfo);
      passInfos.add(passInfo);
      ServantAnalysisInterviewVo interviewInfo = new ServantAnalysisInterviewVo();
      BeanUtils.copyProperties(dataResp,interviewInfo);
      interviewInfos.add(interviewInfo);
      ServantAnalysisPositionVo positionInfo  = new ServantAnalysisPositionVo();
      BeanUtils.copyProperties(dataResp,positionInfo);
      positionInfos.add(positionInfo);
    }
    result.setPassInfo(passInfos);
    result.setInterviewInfo(interviewInfos);
    result.setPositionInfo(positionInfos);
  }

  /**
   * 按面试统计成绩分析
   * @param query
   * @return
   */
  private List<InterviewAnalysisDataVo>  handleServantGradeAnalysisDataInterview(QueryExamineeGradeVo query) {
    Map<String,List<ServantInterviewAnalysisDataResp>>  dataMap ;
    ServantInterviewAnalysisData queryData = new ServantInterviewAnalysisData();
    queryData.setExamId(query.getExamId());
    queryData.setExamNameConfigId(query.getExamNameConfigId());
    queryData.setExamYear(query.getExamYear());
    List<InterviewAnalysisDataVo> lists = new ArrayList<>();
    List<ServantInterviewAnalysisDataResp> data =   servantInterviewAnalysisDataService.getServantInterviewAnalysisData(queryData);
    List<ServantInterviewAnalysisDataResp> totals =   servantInterviewAnalysisDataService.getServantInterviewAnalysisDataByPositionTier(queryData);
    if(CollectionUtils.isNotEmpty(data)){
      dataMap = data.stream().collect(Collectors.groupingBy(t -> t.getPositionTier()));
      Map<String,ServantInterviewAnalysisDataResp>  totalsMap =   totals.stream().collect(Collectors.toMap(ServantInterviewAnalysisDataResp::getPositionTierName, e -> e));
      Iterator<Map.Entry<String,List<ServantInterviewAnalysisDataResp>>> iterators = dataMap.entrySet().iterator();
      while(iterators.hasNext()){
        Map.Entry<String,List<ServantInterviewAnalysisDataResp>> entry = iterators.next();
        String key = entry.getKey();
        List<ServantInterviewAnalysisDataResp> list = entry.getValue();
        String positionTierName = CollectionUtils.isNotEmpty(list) ? list.get(0).getPositionTierName() : "";
        if (totalsMap.containsKey(key)) {
          ServantInterviewAnalysisDataResp totalResp = totalsMap.get(key);
          totalResp.setZwlbName("合计");
          list.add(totalResp);
        }
        InterviewAnalysisDataVo dataVo = new InterviewAnalysisDataVo(positionTierName,list);
        lists.add(dataVo);
      }
    }
    return lists ;
  }



  /**
   * 按层级
   * @param query
   * @return
   */
  private List<ServantPassAnalysisDataVo>  handleServantGradeAnalysisDataPass(QueryExamineeGradeVo query) {
    Map<String,List<ServantPassAnalysisData>>  dataMap ;
    ServantPassAnalysisData queryData = new ServantPassAnalysisData();
    queryData.setExamId(query.getExamId());
    queryData.setExamNameConfigId(query.getExamNameConfigId());
    queryData.setExamYear(query.getExamYear());
    List<ServantPassAnalysisDataVo> dataVos = new ArrayList<>();
    List<ServantPassAnalysisData>  data =   servantPassAnalysisDataService.selectServantPassAnalysisDataList(queryData);
    if(CollectionUtils.isNotEmpty(data)) {
      dataMap = data.stream().collect(Collectors.groupingBy(t -> t.getPositionTier()));
      Iterator<Map.Entry<String,List<ServantPassAnalysisData>>> iterators = dataMap.entrySet().iterator();
      while(iterators.hasNext()){
        Map.Entry<String,List<ServantPassAnalysisData>> entry = iterators.next();
        List<ServantPassAnalysisData> list = entry.getValue();
        if (CollectionUtils.isEmpty(list)) {
          continue;
        }
        Long examineeNumTotal = 0L, passNumTotal = 0L, malePassNumTotal = 0L;
        String positionTierName = list.get(0).getPositionTierName();
        for (ServantPassAnalysisData data1 : list) {
          examineeNumTotal += data1.getExamineeNum() == null ? 0 : data1.getExamineeNum();
          passNumTotal += data1.getPassNum() == null ? 0 : data1.getPassNum();
          malePassNumTotal += data1.getMalePassNum() == null ? 0 : data1.getMalePassNum();
          // todo 层级回写，前端取了此字段
          data1.setPositionTier(data1.getPositionTierName());
        }
        BigDecimal passRateTotal = examineeNumTotal==0L ? BigDecimal.ZERO : MathUtils.setScale(passNumTotal.doubleValue() /examineeNumTotal,4)  ;
        BigDecimal malePassRateTotal = passNumTotal==0L ? BigDecimal.ZERO:   MathUtils.setScale(malePassNumTotal.doubleValue() /passNumTotal,4);
        ServantPassAnalysisData totalData = new ServantPassAnalysisData();
        totalData.setPositionTier("合计");
        totalData.setExamineeNum(examineeNumTotal);
        totalData.setPassNum(passNumTotal);
        totalData.setMalePassNum(malePassNumTotal);
        totalData.setPassRate(passRateTotal);
        totalData.setMalePassRate(malePassRateTotal);
        list.add(totalData);
        ServantPassAnalysisDataVo dataVo = new ServantPassAnalysisDataVo(positionTierName,list);
        dataVos.add(dataVo);
      }
    }
    return dataVos;
  }

}